package main

import (
	"fmt"
	"log"
	"net/http"
	"strings"
	"time"

	"github.com/gcz/go_web/session"

	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

type Person struct {
	user_name string
	_id       int32
}

type Student struct {
	ID         int32  `bson:"_id"`
	CreateTime int32  `bson:"ctime"`
	Mobile     string `bson:"mobile"`
	Unionid    string `bson:"unionid"`
	MyID       int32  `bson:"my_id"`
	Utime      int32  `bson:"utime"`
}

func sayhelloName(w http.ResponseWriter, r *http.Request) {

	expiration := time.Now()
	expiration = expiration.AddDate(1, 0, 0)
	cookie := http.Cookie{Name: "username", Value: "guchenzhe", Expires: expiration, Path: "/", HttpOnly: false, MaxAge: 86400}
	fmt.Println(cookie)
	http.SetCookie(w, &cookie)
	r.ParseForm() // 解析请求参数,默认不会解析参数
	fmt.Println("path", r.URL.Path)
	fmt.Println("scheme", r.URL.Scheme)
	fmt.Print(r.Form["url_long"])
	for k, v := range r.Form {
		fmt.Print("key:", k)
		fmt.Print("val:", strings.Join(v, ""))
	}
	fmt.Fprintf(w, "Hello Gu chen zhe!!!") // w是输出到客户端的

	// clientCookie, _ := r.Cookie("username")
	// fmt.Fprint(w, clientCookie)
	// fmt.Println(clientCookie)
	// for _, cCookie := range r.Cookies() {
	// 	fmt.Fprint(w, cCookie.Name)
	// }
}

var globalSessions *session.Manager

func init() {
	globalSessions, _ = session.NewManager("memory", "gosessionid", 3600)
}

func login(w http.ResponseWriter, r *http.Request) {
	fmt.Print("------globalSessions:", globalSessions)
	sess := globalSessions.SessionStart(w, r)
	r.ParseForm()
	if r.Method == "GET" {
		fmt.Fprint(w, sess.Get("username"))
	} else {
		fmt.Println("POST")
		sess.Set("username", r.Form["username"])
	}
}

func main() {
	http.HandleFunc("/", sayhelloName)
	http.HandleFunc("/login", login)
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		log.Fatal("ListenAndServer:", err)
	}
}

func mgoTest() {
	// session, err := mgo.Dial("localhost")
	session, err := mgo.Dial("mongodb://root:swtech2016@dev.yanzijia.cn:3717")
	if err != nil {
		panic(err)
	}
	defer session.Close()

	session.SetMode(mgo.Monotonic, true)

	c := session.DB("myedu_dev").C("student")
	result := Student{}
	err = c.Find(bson.M{"_id": 100008}).One(&result)
	// err = c.Insert(&Person{"Ale", "+55 53 8116 9639"},
	// &Person{"Cla", "+55 53 8402 8510"})
	// if err != nil {
	// 	panic(err)
	// }

	// result := Person{}
	// err = c.Find(bson.M{"name": "Ale"}).One(&result)
	if err != nil {
		panic(err)
	}

	// fmt.Println("teacher_name:", result.user_name)
	fmt.Println("result", result)
}
